<template>
  <basic-container>
    <avue-crud class="trainarchive_crud"
               :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   @click="handleDelete">删 除
                   <!-- v-if="permission.trainarchive_delete" -->
        </el-button>
        <el-button type="success"
                   size="small"
                   plain
                   icon="el-icon-upload2"
                   @click="handleImport">导入
                   <!-- v-if="permission.prod_unit_import" -->
        </el-button>
        <el-button type="warning"
                   size="small"
                   plain
                   icon="el-icon-download"
                   @click="handleExport">导出
                   <!-- v-if="permission.prod_unit_export" -->
        </el-button>
      </template>
      <template slot="zswjForm">
        <div>
            <el-upload
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="zswjFileList"
              :before-upload="zswjBeforeUpload"
              :on-remove="zswjHandleRemove"
              :on-success="zswjUploadSuccess"
            >
              <el-button size="small" type="primary">选择文件</el-button>
            </el-upload>
          </div>
      </template>
      <template slot="yxq" slot-scope="scope">
        <span>{{yxqFormatter(scope.row.yxqq, scope.row.yxqz)}}</span>
      </template>
      <template slot="zjpxsj" slot-scope="scope">
        <span>{{dateFormatter(scope.row.zjpxsj)}}</span>
      </template>
      <template slot="xcpxsj" slot-scope="scope">
      <span>{{dateFormatter(scope.row.xcpxsj)}}</span>
      </template>
    </avue-crud>

    <!-- 导入弹窗 -->
      <el-dialog
        title="导入"
        append-to-body
        :visible.sync="excelBox"
        width="555px"
      >
        <avue-form
          :option="excelOption"
          v-model="excelForm"
          :upload-after="uploadAfter"
          :upload-before="beforeUpload"
          :upload-error="uploadError"
        >
          <template slot="excelTemplate">
            <el-button type="primary" @click="handleTemplate">
              点击下载<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </template>
        </avue-form>
      </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/jypx/edutrainarchive/trainarchive";
  import {mapGetters} from "vuex";
  import { getToken } from "@/util/auth";
  import moment from 'moment';

  export default {
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          labelWidth: 100,
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          indexLabel:'序号',
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "人员名称",
              prop: "rymc",
              align: "center",
              search: true,
              rules: [{
                required: true,
                message: "请输入人员名称",
                trigger: "blur"
              }]
            },
            {
              label: "人员在职状态",
              prop: "zzzt",
              align: "center",
              type: "select",
              dicData: [
                {
                  label: "在职",
                  value: 1
                },
                {
                  label: "离职",
                  value: 2
                }
              ]
            },
            {
              label: "人员职务",
              align: "center",
              prop: "ryzw"
            },
            {
              label: "作业类型",
              align: "center",
              prop: "zylx",
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=edu_train_archive_zylx",
              props: {
                    label: "dictValue",
                    value: "dictKey"
                  },
              dataType: "number"
            },
            {
              label: "证书名称",
              align: "center",
              prop: "zsmc"
            },
            {
              label: "证书编号",
              align: "center",
              prop: "zsbh"
            },
            {
              label:'有效期',
              align: "center",
              prop:'yxq',
              width: 160,
              slot: true,
              display: false
            },
            {
              label: "有效期(起)",
              prop: "yxqq",
              type: 'datetime',
              rules: [{
                required: true,
                message: "请选择有效期(起)",
                trigger: "blur"
              }],
              // valueFormat: 'yyyy-MM-dd',
              hide: true
            },
            {
              label: "有效期(止)",
              prop: "yxqz",
              type: 'datetime',
              rules: [{
                required: true,
                message: "请选择有效期(止)",
                trigger: "blur"
              }],
              // valueFormat: 'yyyy-MM-dd',
              hide: true
            },
            {
              label: "最近培训时间",
              prop: "zjpxsj",
              align: "center",
              type: 'datetime',
              width: 160,
              slot: true
            },
            {
              label: "下次培训时间",
              prop: "xcpxsj",
              align: "center",
              type: 'datetime',
              width: 160,
              slot: true
            },
            {
              label: "发证机关",
              prop: "fzjg"
            },
            {
              label: "证书描述",
              prop: "zsms",
              hide: true
            },
            {
              label: "证书文件",
              prop: "zswj",
              align: "center",
              span: 12,
              slot: true,
              viewDisplay: false,
              formslot: true,
              // props: {
              //   label: 'zswj',
              //   value: 'zswj'
              // },
              hide: true
            }
          ]
        },
         // 附件
        zswjFileList: [],
        SetHeaders: { "Blade-Auth": getToken() },
        data: [],
        // 导入
        excelBox: false,
        excelForm: {},
        excelOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: "模板上传",
              prop: "excelFile",
              type: "upload",
              drag: true,
              loadText: "模板上传中，请稍等",
              showFileList: false,
              span: 24,
              propsHttp: {
                fileName: "multipartFile",
                res: "data"
              },
              tip: "请上传 .xls,.xlsx 标准格式文件",
              action: "/api/eduTrainArchive/trainarchive/importTrainArchive"
            },
            {
              label: "模板下载",
              prop: "excelTemplate",
              formslot: true,
              span: 24
            }
          ]
        },
        isFailed: false
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          // addBtn: this.vaildData(this.permission.trainarchive_add, false),
          // viewBtn: this.vaildData(this.permission.trainarchive_view, false),
          // delBtn: this.vaildData(this.permission.trainarchive_delete, false),
          // editBtn: this.vaildData(this.permission.trainarchive_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      dateFormatter(date) {
        if (!date) {
          return ""
        }
        return moment(date).format('YYYY-MM-DD HH:mm:ss');
      },
      yxqFormatter: (startValidData, endValidData) => {
        return moment(startValidData).format('YYYY-MM-DD') + "~" + moment(endValidData).format('YYYY-MM-DD');
      },
      // 导入前判断
      beforeUpload(file, done, loading) {
        this.isFailed = false;
        var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
        const extension = testmsg === "xls";
        const extension2 = testmsg === "xlsx";
        if (!extension && !extension2) {
          this.$message.warning("请上传 .xls,.xlsx 标准格式文件!");
          loading();
        } else {
          done();
        }
      },

      // 模板下载
      handleTemplate() {
        window.open(`/api/eduTrainArchive/trainarchive/downLoadTemplate?${this.website.tokenHeader}=${getToken()}`);
      },

      // 导入失败后
      uploadError(error, column) {
        console.log(error, column);
        this.isFailed = true;
      },

      // 导入成功后
      uploadAfter(res, done) {
        done();
        if (this.isFailed === true) {
          return;
        }
        this.excelBox = false;
        this.$message.success("上传成功");
        this.cancle();
      },
      // 取消
      cancle() {
        this.page.currentPage = 1;
        this.onLoad(this.page);
      },
      
      rowSave(row, done, loading) {
        if (new Date(row.yxqq).getTime() >= new Date(row.yxqz).getTime()) {
					this.$message.warning('有效开始日期不能晚于或等于结束日期！');
          loading();
					return
				}
        if (row.zjpxsj && new Date(row.zjpxsj).getTime() >= new Date().getTime()) {
					this.$message.warning('最近培训时间日期不能晚于或等于当前时间！');
          loading();
					return
				}
        if (row.xcpxsj && new Date(row.xcpxsj).getTime() < new Date().getTime()) {
					this.$message.warning('下次培训时间日期不能早于当前时间！');
          loading();
					return
				}
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        if (new Date(row.yxqq).getTime() >= new Date(row.yxqz).getTime()) {
					this.$message.warning('有效开始日期不能晚于或等于结束日期！');
          loading();
					return
				}
        if (row.zjpxsj && new Date(row.zjpxsj).getTime() >= new Date().getTime()) {
					this.$message.warning('最近培训时间日期不能晚于或等于当前时间！');
          loading();
					return
				}
        if (row.xcpxsj && new Date(row.xcpxsj).getTime() < new Date().getTime()) {
					this.$message.warning('下次培训时间日期不能早于当前时间！');
          loading();
					return
				}
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
            // 反显上传文件
            this.zswjFileList = []
            if (this.form) {
              const lastIndex = this.form.zswj.lastIndexOf('/')
              const fileName = this.form.zswj.slice(lastIndex + 1)
              const now = new Date()
              const obj = { name: fileName,
                            raw: {
                              lastModified: now.getTime(),
                              lastModifiedDate: now,
                              name: fileName,
                              uid: now.getTime(),
                              webkitRelativePath: ""
                            },

                          }
              this.zswjFileList.push(obj)
            }
          });
        }
        if (type == "add") {
          for(let key in this.form){
            this.form[key] = null;
          }
          this.zswjFileList = []
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      uploadAfter(res, done, loading) {
        done()
      },
      // 上传附件前
      zswjBeforeUpload(file) {
        var isLimit = this.zswjFileList.length + 1 <= 1;
        if (!isLimit) {
          // this.$message.warning("只能选择一个附件!");
          // 清空文件list
          // this.zswjFileList = []
          return true
        }
        return isLimit;
      },
      // 删除附件
      zswjHandleRemove(file, fileList) {
        this.zswjFileList = fileList;
        this.form.zswj = "";
      },
      zswjUploadSuccess(response, file, fileList) {
        if (response.code !== 200 || response.success !== true) {
          return;
        }
        this.zswjFileList = fileList;
        // 删除原来的文件对象
        if (this.zswjFileList.length > 1) {
          this.zswjFileList.splice(0,1);
        }
        this.form.zswj = response.data.filePath;
      },
      handleImport() {
        this.excelBox = true;
      },
      handleExport() {
        this.$confirm("是否导出?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          let rymc = this.query.rymc !== undefined && this.query.rymc !== "" && this.query.rymc !== null ? this.query.rymc : "";
          window.open(`/api/eduTrainArchive/trainarchive/exportTrainArchive?${this.website.tokenHeader}=${getToken()}&rymc=${rymc}`);
        });
      }
    }
  };
</script>

<style>
.anchorBL {
  display: none;
}
</style>
